package org.koyad.portal.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.misc.PortalPage;
import org.koyad.portal.tags.ViewRoot;
import org.koyad.portal.utils.LogUtils;
import org.koyad.portal.vo.PageMetaData;

@WebFilter (
		filterName = "PortalPageFilter", 
		urlPatterns = { 
			"/" + FrameworkConstants.PISTON_PORTAL_PAGES + "/*"
		}
)
public class PortalPageFilter extends BaseFilter {

	private static final LogUtils LOGGER = LogUtils.getLogger(PortalPageFilter.class);

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		
		LOGGER.startMethod("doFilter");
		
		HttpServletRequest httpReq = (HttpServletRequest)req;
		HttpServletResponse httpResp = (HttpServletResponse)resp;
		
		try {
			
			super.doFilter(req, resp, chain);
			
			String _uri = httpReq.getRequestURI();
			int mappingIndex = _uri.indexOf(FrameworkConstants.PISTON_PORTAL_PAGES);
			int slashIndex = _uri.indexOf('/', mappingIndex);
			int nextSlashIndex = _uri.indexOf('/', slashIndex + 1);
			
			String pageIdORMapping = "";
			if(nextSlashIndex > -1) {
				pageIdORMapping = _uri.substring(slashIndex + 1, nextSlashIndex);
			} else {
				pageIdORMapping = _uri.substring(slashIndex + 1);
			}
			
			PortalPage portalPage = new PortalPage(pageIdORMapping);
			PageMetaData page = null;
			if(null != portalPage.getPageMapping()) {
				page = new PageMetaData(portalPage, null);
			}
			
			if (null != page) {
				
				if (page.getPortalPage().isProted() && null == httpReq.getUserPrincipal()) {
					PageUtils.setLogin(httpReq, httpResp);
				} else {
					ViewRoot currentViewRoot = PistonContext.getContext().getViewRoot();
					if(null == currentViewRoot || !currentViewRoot.getMetaData().equals(page)) {
						LOGGER.info("Creating view tree for portal theme -> " + page.getPortalPage().getFrame());
						PageUtils.createViewRoot(page);
					}
				}
				chain.doFilter(req, resp);
				
			} else {
				PageUtils.include("/NotFound.html", httpReq, httpResp);
			}
				
		} catch (FrameworkException e) {
			LOGGER.logException(e);
			PageUtils.include("/Error.html", httpReq, httpResp);
		}
		
		LOGGER.endMethod("doFilter");

	}

}
